import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { 
  Table, 
  Button, 
  Icon, 
  Row, 
  Col, 
  Tooltip, 
  Divider, 
  Input, 
  Popconfirm, 
  message, 
  Form, 
  Select, 
  DatePicker, 
  Dropdown, 
  Menu, 
  Switch, 
  Radio, 
  Pagination, 
  LocaleProvider, 
  Tag,
  Spin
} from 'antd'
import PubSub from 'pubsub-js'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsLogActions } from 'reduxs'
import moment from 'moment'
import _ from 'lodash'
import Modal from 'kenote-react-admin-modal'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag } from 'services/utils'
import TagSelect from 'ant-design-pro/lib/TagSelect'
import { PageNotFound } from 'components'
import history from 'store/history'
import zhCN from 'antd/lib/locale-provider/zh_CN'
import { HttpServices, REDUX_FETCH_TIMEOUT } from 'services/utils'
import { getToken } from 'services/token'
import fetchMock from 'fetch-mock'

const FormItem = Form.Item
const Option = Select.Option
const RangePicker = DatePicker.RangePicker
const RadioGroup = Radio.Group
const RadioButton = Radio.Button
const accessFlag = getPageFlag('/admins/logs', 'access')

@connect(
  state => ({
    getListPending      : state.AdminsLog.getListPending,
    getListError        : state.AdminsLog.getListError,
    getListMessage      : state.AdminsLog.getListMessage,
    listData            : state.AdminsLog.listData,
    Options             : state.AdminsLog.options,
    auth                : state.Passport.auth,
  }),
  dispatch => ({
    actions: bindActionCreators({...adminsLogActions}, dispatch)
  })
)
export default class AdminsLogs extends PureComponent {
  
  render () {
    const { location, getListPending, Options, getListError, listData } = this.props
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '帐号管理' },
        { name: '日志管理' }
      ],
      errCode: getListError
    }
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 100,
        //fixed: 'left'
      },
      {
        title: '账号',
        dataIndex: 'user',
        key: 'user',
        width: 150,
        render: (user) => _.has(user, 'username') ? user.username : '--',
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 150,
      },
      {
        title: '操作详情',
        dataIndex: 'content',
        key: 'content',
      },
      {
        title: '执行时间',
        dataIndex: 'createAt',
        key: 'createAt',
        width: 180,
        render: (createAt) => (<span>{moment(createAt).format('YYYY-MM-DD HH:mm:ss')}</span>) ,
      },
    ]
    const dataSource = getDataSource(listData, { 
      key: '_id', 
      //query: o => o.level > 1000,
      //order: [['id', 'level'], ['asc', 'desc']] 
    })
    return (
      <LocaleProvider locale={zhCN} >
        <CoreLayout {...options}>
          <AdvancedSearchForm 
            Options={Options}
            loading={getListPending}
            onSubmit={this.handleSubmit}
            />
          <Table 
            //rowSelection={rowSelection}
            columns={columns} 
            dataSource={dataSource} 
            loading={getListPending} 
            pagination={false} 
            //bordered={true} 
            //scroll={{ x: 1692 }}
            size="middle"
          />

          {Options && (
            <div style={{ textAlign: 'right', margin: '12px 0' }}>
              {Options.counts > 0 && (
                <Pagination 
                  showQuickJumper 
                  current={Options.page} 
                  total={Options.counts || 0} 
                  //showTotal={(total, range) => `[${_.join(range, ' - ')}], 共 ${total} 条记录 `}
                  pageSize={Options.page_size || 0} 
                  onChange={this.handleChangePage}
                  />
              )}
            </div>
          )}
        </CoreLayout>
      </LocaleProvider>
    )
  }

  handleSubmit = (values) => {
    console.log(values)
    this.props.actions.getlist(values)
  }

  handleChangePage = (page) => {
    this.props.actions.getlist({ ...this.props.Options, page })
  }
}


@Form.create()
class AdvancedSearchForm extends PureComponent {

  static propTypes = {
    Options: PropTypes.object,
    onSubmit: PropTypes.func,
    loading: PropTypes.bool,
  }

  static defaultProps = {
    Options: null,
    onSubmit: () => null,
    loading: false,
  }

  constructor (props) {
    super(props)
    this.state = {
      usersData: null,
      fetching: false,
      usersValue: _.has(props.Options, 'user') ? props.Options['user'] : []
    }
  }

  render () {
    const { form, Options, loading } = this.props
    const { getFieldDecorator } = form
    let create_time = [undefined, undefined]
    if (_.has(Options, 'create_time')) {
      create_time = []
      let create_time_arr = Options.create_time.split('|')
      for (let e of create_time_arr) {
        create_time.push(moment(moment(Number(e)).format('YYYY-MM-DD HH:mm')))
      }
    }
    return (
      <Form
        className="ant-advanced-search-form"
        onSubmit={this.handleSubmit}
        >
        <div className="content">
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>时间段</span>)}
            >
            {getFieldDecorator('create_time', {
              initialValue: create_time
            })(
              <RangePicker
                showTime={{ format: 'HH:mm' }}
                format="YYYY-MM-DD HH:mm"
                />
            )}
          </FormItem>
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>类型</span>)}
            >
            {getFieldDecorator('type', {
              initialValue: _.has(Options, 'type') ? Options.type : 'all'
            })(
              <RadioGroup>
                <RadioButton value="all">全部</RadioButton>
                <RadioButton value="login:api_v1">后台登录</RadioButton>
                <RadioButton value="proto">接口请求</RadioButton>
                <RadioButton value="other">其它操作</RadioButton>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>账号</span>)}
            >
            {getFieldDecorator('user', {
              initialValue: this.state.usersValue
            })(
              <Select
                //defaultValue={this.state.roleId}
                style={{ width: 764 }}
                //onSelect={this.handleChangeRoleId}
                mode="multiple"
                labelInValue
                //value={this.state.usersValue || ['5aab8dc454798be4eabc96f6']}
                placeholder="查找相关账号..."
                notFoundContent={this.state.fetching ? <Spin size="small" /> : null}
                filterOption={false}
                onSearch={this.handleFetchUser}
                onChange={this.handleChangeUser}
                >
                {this.state.usersData && this.state.usersData.map( (item, i) => {
                  return (
                    <Option key={item._id}>{item.username}</Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
        </div>
        <Divider style={{ marginTop: 0 }} />
        <Row>
          <Col span={20}>
            <Button type="primary" htmlType="submit" loading={loading}>高级查询</Button>
            
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            
          </Col>
        </Row>
      </Form>
    )
  }

  handleSubmit = e => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let options = _.pick(values, ['type'])
        if (values.create_time) {
          let create_time = []
          for (let item of values.create_time) {
            item && create_time.push(moment(item).format('x'))
          }
          if (create_time.length > 0) {
            options = { ...options, create_time: _.join(create_time, '|') }
          }
        }
        options = { ...options, user: this.state.usersValue }
        this.props.onSubmit(options)
      }
    })
  }

  handleFetchUser = (value) => {
    this.setState({ fetching: true })
    setTimeout(async () => {
      try {
        const token = getToken()
        const header = {
          Authorization: token
        }
        const result = await HttpServices.GET(`/admins/user/find`, { username: value }, header)
        fetchMock.restore()
        const { data, status } = result
        this.setState({ usersData: data, fetching: false })
      } catch (error) {
        this.setState({ fetching: false })
      }
    }, REDUX_FETCH_TIMEOUT)
  }

  handleChangeUser = (value) => {
    this.setState({ usersValue: value })
  }
}